<template>
  <a-spin :spinning="spinning" tip="加载中...">
    <a-card :bordered="false">
      <h3 style="margin-bottom: 20px">{{ id == 'null' ? '新增' : '编辑' }}海报</h3>
      <a-form-model ref="rulesForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 4 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
        <a-form-model-item label="活动标题" prop="posterName">
          <a-input v-model.trim="form.posterName" :maxLength="20" placeholder="最多输入20字" allowClear />
        </a-form-model-item>
        <a-form-model-item label="跳转链接" prop="posterRedirectUrl">
          <a-input v-model.trim="form.posterRedirectUrl" placeholder="请输入跳转链接" allowClear />
        </a-form-model-item>
        <a-form-model-item label="可见店铺" prop="storeIds">
          <a-tree-select
            v-model="form.storeIds"
            style="width: 70%"
            :dropdownStyle="{ maxHeight: '476px' }"
            :tree-data="treeData"
            tree-checkable
            allowClear
            placeholder="请选择或导入"
            search-placeholder="Please select"
          />
          <a-upload
            accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            name="file"
            :showUploadList="false"
            :multiple="false"
            :data="uploadData"
            :action="uploadUrl"
            @change="onChange"
          >
            <a-button style="margin-left: 8px" type="primary">导入</a-button>
          </a-upload>
          <a-button style="margin-left: 8px; vertical-align: top" @click="handleDownload" type="primary">模板下载</a-button>
        </a-form-model-item>

        <a-form-model-item label="海报" prop="posterUrl">
          <JImageUpload
            :uploadParams="getUploadParams()"
            :isMove="false"
            :isMultiple="true"
            :fileSize="2"
            :number="1"
            :accept="'image/*'"
            @fileChange="filePosterUrlChange"
            v-model="posterUrlList"
          ></JImageUpload>
          <div>图片小于2M，格式jpg、png，建议像素900x1200px。</div>
        </a-form-model-item>
        <a-form-model-item label="是否上架" prop="status"> <a-switch v-model="form.status" /> 打开开关，活动创建完成立即上架。 </a-form-model-item>
        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button @click="handleBack">取消</a-button>
          <a-button @click="handleSubmit" style="margin-left: 10px" type="primary">确认添加</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-card>
  </a-spin>
</template>
<script>
import JImageUpload from '../components/JImageUpload'
import { posterConfigEdit, posterConfigDetail, storeList, storePackageImport } from '@/api/pos/posterConfiguration'
import { mapGetters } from 'vuex'
export default {
  components: {
    JImageUpload
  },
  data() {
    return {
      id: this.$route.params.id,
      checkAll: true,
      brandList: [],
      storeAreas: [],
      uploadData: {},
      uploadUrl: storePackageImport,
      treeData: [],
      posterUrlList: [],
      spinning: false,
      form: {
        posterUrl: '',
        storeIds: [],
        status: false,
        storePackageId: ''
      },
      rules: {
        posterName: [{ required: true, message: '请输入', trigger: 'blur' }],
        posterRedirectUrl: [{ required: true, message: '请输入', trigger: 'blur' }],
        status: [{ required: true, message: '请选择', trigger: 'change' }],
        posterUrl: [{ required: true, message: '请选择', trigger: 'change' }],
        storeIds: [{ required: true, message: '请选择或导入', trigger: 'change' }]
      }
    }
  },
  watch: {},
  created() {
    this.getDetails()
    this.getStoreList()
  },
  computed: {},
  mounted() {},
  methods: {
    // 模板下载
    handleDownload() {
      window.location.href = 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20220804/0034d78726a423cdcdcf95c755319748.xlsx'
    },

    // 获取门店列表
    getStoreList() {
      storeList().then(res => {
        if (res.code === 200) {
          this.treeData = this.formatStore(res.data)
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 格式化门店
    formatStore(list) {
      let treeData = []
      list.forEach(e => {
        const brandItem = {
          title: e.brandName,
          value: e.brandId,
          key: e.brandId,
          children: []
        }
        e.areaVos.forEach(i => {
          const areaItem = {
            title: i.areaName,
            value: i.areaId + e.brandId,
            key: i.areaId + e.brandId,
            children: []
          }
          brandItem.children.push(areaItem)
          i.storeList.forEach(j => {
            const storeItem = {
              title: j.storeName,
              value: j.storeId,
              key: j.storeId
            }
            areaItem.children.push(storeItem)
          })
        })
        treeData.push(brandItem)
      })
      return treeData
    },

    // 导入门店
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        const { msg, message, code, data } = info.file.response
        if (code == 200) {
          this.form.storeIds = data.storeList.map(e => e.storeId)
          this.$refs.rulesForm.validateField(['storeIds'])
        } else {
          this.$message.error(msg || message)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
    },

    // 获取详情
    getDetails() {
      if (this.id == 'null') return
      const data = {
        posterId: this.id
      }
      posterConfigDetail(data)
        .then(res => {
          if (res.code === 200) {
            const { posterUrl, storeList, storeIds, status } = res.data
            let currentStoreIds = []
            if (storeIds) {
              storeIds.forEach(e => {
                currentStoreIds.push(e)
              })
            }
            if (storeList) {
              storeList.forEach(e => {
                currentStoreIds.push(e.storeId)
              })
            }
            this.form = {
              ...res.data,
              storeIds: currentStoreIds,
              status: status == 'Y' ? true : false
            }
            this.posterUrlList = posterUrl ? posterUrl.split(',') : []
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
        .catch(err => {})
    },

    getUploadParams() {
      return {
        actionUrl: 'https://jic.jnby.com/activity/market-act/common/upload/multipart',
        headers: {
          authorization: 'authorization-text'
        },
        uploadHost: 'https://img.bzhz.jnbygroup.com/'
      }
    },

    // 图片change
    filePosterUrlChange(list) {
      this.form.posterUrl = list.length ? list[0].url : ''
      this.$refs.rulesForm.validateField(['posterUrl'])
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),

    // 确认
    handleSubmit() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          const { status } = this.form
          const data = {
            ...this.form,
            status: status ? 'Y' : 'N',
            linkId: this.userInfo().workNo
          }
          this.spinning = true
          posterConfigEdit(data)
            .then(res => {
              if (res.code === 200) {
                this.$router.go(-1)
              } else {
                this.spinning = false
                this.$message.error(res.msg || res.message)
              }
            })
            .catch(err => {
              this.spinning = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    //返回
    handleBack() {
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.my-img-item {
  margin: 0 8px 8px 0;
}
/deep/.ant-checkbox-wrapper {
  margin-right: 8px;
  margin-left: 0;
}

/deep/ .ant-select-selection--multiple {
  max-height: 180px;
  overflow: hidden;
  overflow-y: auto;
}
/deep/ .ant-upload.ant-upload-select {
  vertical-align: top;
}
</style>
